package titt.server.service.db;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import titt.key.TITTKey;
import titt.server.service.Service;

public class MappedServerDatabase implements ServerDatabase {

	private final Map<String, Service> 	idMap = new HashMap<String, Service>(),
										keyMap = new HashMap<String, Service>();
	
	private final SortedSet<Service> services = new TreeSet<Service>();
	
	@Override
	public synchronized void add(Service s) {
		idMap.put(s.getID(), s);
		keyMap.put(s.getKey().asKeyString(), s);
		
		services.add(s);
	}

	@Override
	public synchronized Service remove(String id) {
		Service s = idMap.remove(id);

		if(s != null) {
			keyMap.remove(s.getKey().asKeyString());
			services.remove(s);
		}
		
		return s;
	}

	@Override
	public synchronized boolean containsDuplicateKey(TITTKey key) {
		return keyMap.containsKey(key.asKeyString());
	}

	@Override
	public synchronized Service get(String id) {
		return idMap.get(id);
	}

	@Override
	public synchronized Service get(TITTKey key) {
		if(keyMap.containsKey(key.asKeyString()))
			return keyMap.get(key.asKeyString());
				
		for(Service s : services)
			if(s.getKey().equivalentTo(key))
				return s;

		return null;
	}

	@Override
	public synchronized Service[] getAll() {
		return services.toArray(new Service[services.size()]);
	}


}
